package f;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.global.opencv_imgcodecs;
import org.bytedeco.opencv.opencv_core.Mat;

public class Vjpg {
	
	private File vfile;
	private List<Integer> randomGrab = Arrays.asList(678, 2345, 3456, 5678, 6789, 7890);

	public Vjpg(String vfile) {
		this.vfile = new File(vfile);
	}
	public Vjpg(File vfile) {
		this.vfile = vfile;
	}
	
	public int rgSize() {
		return randomGrab.size();
	}
	
	public boolean support() {
		String f_type = FileExt.getType(vfile);
		return FileExt.T3.equals(f_type);
	}
	
	public static String getJpgName(File vfile, int n) {
		return FileExt.getNameWithoutExt(vfile)+"-"+n+".jpg";
	}
	
	public void createJpg() throws Exception {
		if(!support()) {
			return;
		}
		
		int size = rgSize();
		int j = 0;
		for(int i=0; i<size; i++) {
			File to = new File(vfile.getParentFile(), getJpgName(vfile, i+1));
			if(to.exists()) {
				randomGrab.set(i, null);
				j++;
			}
		}
		if(randomGrab.size()==j) {
			return;
		}
		
		FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(vfile.getAbsolutePath());
        ff.start();
        
        int ffLength = ff.getLengthInFrames();
        int maxRandomGrab = randomGrab.get(randomGrab.size() - 1);
        Frame f = null;
        int i = 0;
        while (i < ffLength) {
            f = ff.grabImage();
            int io = randomGrab.indexOf(i);
            if (io!=-1) {
                if(f!=null && f.image!=null) {
                	OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
                	Mat mat = converter.convertToMat(f);
                	File to = new File(vfile.getParentFile(), getJpgName(vfile, io+1));
                	opencv_imgcodecs.imwrite(to.getAbsolutePath(), mat);
                }
            }
            if (i >= maxRandomGrab) {
                break;
            }
            i++;
        }
        ff.stop();
	}
	
	public static void main(String[] args) throws Exception {
		if(args!=null && args.length>0) {
			for(String arg: args) {
				new Vjpg(arg).createJpg();
			}
		}
	}

}
